<template>
    <div class="organization-chart">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <pageTitle :title="'組織架構圖'" />
                    <div class="header-actions">
                        <el-button type="primary" @click="handleAddOrganization">
                            <el-icon>
                                <Plus />
                            </el-icon>新增組織
                        </el-button>
                        <el-button type="success" @click="handleDownloadChart">
                            <el-icon>
                                <Download />
                            </el-icon>下載
                        </el-button>
                    </div>
                </div>
            </template>

            <div class="chart-container" :style="{ transform: `scale(${zoomLevel / 100})` }">
                <vue3-tree-org :data="orgData" :horizontal="false" :collapsable="true" :node-draggable="true"
                    :only-one-node="false" :default-expand-level="1" @on-contextmenu="onContextMenu"
                    @on-node-click="onNodeClick">
                    <template #default="{ node }">
                        <div class="org-node" :class="{
                            'org-node-root': node.id === 1,
                            'org-node-disabled': node.disabled,
                            'org-node-no-drag': node.noDragging
                        }">
                            <div class="org-node-header">
                                <div class="org-name">{{ node.label }}</div>
                                <div class="org-info-line">
                                    <el-icon>
                                        <User />
                                    </el-icon>
                                    <span>負責人: {{ node.leader }}</span>
                                </div>
                                <div class="org-info-line">
                                    <el-icon>
                                        <User />
                                    </el-icon>
                                    <span>編制/員工: {{ node.staffingCount }}/{{ node.employeeCount }}</span>
                                </div>
                            </div>
                            <div class="org-node-body">
                                <el-tag v-if="node.departmentType" size="small" :type="getTagType(node.departmentType)">
                                    {{ getDepartmentTypeName(node.departmentType) }}
                                </el-tag>
                            </div>
                        </div>
                    </template>
                </vue3-tree-org>
            </div>
        </el-card>

        <!-- 新增組織對話框 -->
        <el-dialog v-model="addDialogVisible" title="新增組織" width="500px">
            <el-form :model="newOrgForm" label-width="100px">
                <el-form-item label="組織名稱" required>
                    <el-input v-model="newOrgForm.name" placeholder="請輸入組織名稱" />
                </el-form-item>
                <el-form-item label="組織類型" required>
                    <el-select v-model="newOrgForm.type" placeholder="請選擇組織類型">
                        <el-option label="公司" value="company" />
                        <el-option label="部門" value="department" />
                        <el-option label="小組" value="team" />
                    </el-select>
                </el-form-item>
                <el-form-item label="負責人">
                    <el-input v-model="newOrgForm.leader" placeholder="請輸入負責人姓名" />
                </el-form-item>
                <el-form-item label="上級組織">
                    <el-select v-model="newOrgForm.parentId" placeholder="請選擇上級組織">
                        <el-option v-for="org in allOrganizations" :key="org.id" :label="org.label" :value="org.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="編制人數">
                    <el-input-number v-model="newOrgForm.staffingCount" :min="0" />
                </el-form-item>
                <el-form-item label="員工人數">
                    <el-input-number v-model="newOrgForm.employeeCount" :min="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmAddOrganization">確認</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { User, Plus, Download } from '@element-plus/icons-vue'
import pageTitle from "@/components/pageTitle/pageTitle.vue"
import html2canvas from 'html2canvas'

// 部門類型映射
const departmentTypes = {
    'company': { name: '公司', color: 'primary' },
    'department': { name: '部門', color: 'success' },
    'team': { name: '小組', color: 'warning' },
    'office': { name: '辦公室', color: 'info' }
}

const getDepartmentTypeName = (type) => departmentTypes[type]?.name || '未知'
const getTagType = (type) => departmentTypes[type]?.color || 'info'

// 組織數據
const orgData = ref({
    id: 1,
    label: '樂康科技股份有限公司',
    departmentType: 'company',
    leader: '王樂康',
    staffingCount: 1000,
    employeeCount: 900,
    children: [
        {
            id: 2,
            label: '產品研發中心',
            departmentType: 'department',
            leader: '張技術',
            staffingCount: 400,
            employeeCount: 380,
            children: [
                {
                    id: 6,
                    label: '前端開發部',
                    departmentType: 'team',
                    leader: '李前端',
                    staffingCount: 80,
                    employeeCount: 75,
                    disabled: true
                },
                {
                    id: 8,
                    label: '後端開發部',
                    departmentType: 'team',
                    leader: '趙後端',
                    staffingCount: 120,
                    employeeCount: 115,
                    noDragging: true
                },
                {
                    id: 10,
                    label: '測試品質部',
                    departmentType: 'team',
                    leader: '錢測試',
                    staffingCount: 60,
                    employeeCount: 55
                }
            ]
        },
        {
            id: 3,
            label: '市場營銷中心',
            departmentType: 'department',
            leader: '孫市場',
            staffingCount: 300,
            employeeCount: 280,
            children: [
                {
                    id: 11,
                    label: '品牌推廣部',
                    departmentType: 'team',
                    leader: '周品牌',
                    staffingCount: 80,
                    employeeCount: 75
                },
                {
                    id: 12,
                    label: '銷售運營部',
                    departmentType: 'team',
                    leader: '吳銷售',
                    staffingCount: 120,
                    employeeCount: 110
                }
            ]
        },
        {
            id: 4,
            label: '行政管理中心',
            departmentType: 'department',
            leader: '鄭行政',
            staffingCount: 200,
            employeeCount: 190,
            children: [
                {
                    id: 13,
                    label: '人力資源部',
                    departmentType: 'team',
                    leader: '王人事',
                    staffingCount: 60,
                    employeeCount: 55
                },
                {
                    id: 14,
                    label: '財務會計部',
                    departmentType: 'team',
                    leader: '馮財務',
                    staffingCount: 40,
                    employeeCount: 38
                }
            ]
        }
    ]
})

// 獲取所有組織列表
const allOrganizations = computed(() => {
    const orgs = []
    const traverse = (node) => {
        orgs.push({
            id: node.id,
            label: node.label
        })
        if (node.children) {
            node.children.forEach(child => traverse(child))
        }
    }
    traverse(orgData.value)
    return orgs
})

// 新增組織相關
const addDialogVisible = ref(false)
const newOrgForm = ref({
    name: '',
    type: 'department',
    leader: '',
    parentId: null,
    staffingCount: 0,
    employeeCount: 0
})

const handleAddOrganization = () => {
    newOrgForm.value = {
        name: '',
        type: 'department',
        leader: '',
        parentId: null,
        staffingCount: 0,
        employeeCount: 0
    }
    addDialogVisible.value = true
}

const confirmAddOrganization = () => {
    // 這裡應該實現實際的添加組織邏輯
    console.log('新增組織:', newOrgForm.value)
    addDialogVisible.value = false
}

// 下載圖表功能
const handleDownloadChart = async () => {
    try {
        const chartElement = document.querySelector('.chart-container')
        const canvas = await html2canvas(chartElement, {
            backgroundColor: '#ffffff',
            scale: 2,
            logging: false,
            useCORS: true
        })

        const link = document.createElement('a')
        link.download = '組織架構圖.png'
        link.href = canvas.toDataURL('image/png')
        link.click()
    } catch (error) {
        console.error('下載圖表失敗:', error)
    }
}

// 節點點擊事件
const onNodeClick = (e, node) => {
    console.log('點擊節點:', node)
}

// 右鍵菜單事件
const onContextMenu = ({ node, command }) => {
    console.log('右鍵點擊節點:', node, command)
}

</script>

<style scoped>
.organization-chart {
    padding: 20px;
}

.box-card {
    max-width: 100%;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-actions {
    display: flex;
    gap: 10px;
}

.chart-container {
    width: 100%;
    height: 600px;
    overflow: auto;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    transform-origin: top left;
}

.org-node {
    width: 220px;
    padding: 12px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    border: 1px solid #dcdfe6;
    transition: all 0.3s;
    cursor: pointer;
}

.org-node:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    border-color: #c0c4cc;
}

.org-node-root {
    background-color: #f0f7ff;
    border-color: #a0cfff;
}

.org-node-disabled {
    background-color: #f5f7fa;
    color: #c0c4cc;
    cursor: not-allowed;
}

.org-node-no-drag {
    cursor: no-drop;
}

.org-node-header {
    display: flex;
    flex-direction: column;
    margin-bottom: 8px;
}

.org-name {
    font-weight: bold;
    font-size: 15px;
    margin-bottom: 6px;
    color: #303133;
}

.org-info-line {
    font-size: 12px;
    color: #606266;
    display: flex;
    align-items: center;
    gap: 4px;
    margin: 2px 0;
}

.org-node-body {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-top: 8px;
}

/* 樹形結構線條樣式 */
:deep(.tree-org-node__content) {
    padding: 10px 0;
}

:deep(.tree-org-line) {
    stroke: #c0c4cc;
    stroke-width: 1.5px;
}

:deep(.tree-org-node__children) {
    padding-left: 40px;
}
</style>